package com.jyu.apts.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.jyu.apts.dto.ItemProcessDto;
import com.jyu.apts.dto.ResultDto;
import com.jyu.apts.dto.TableDto;
import com.jyu.apts.dto.UserDto;
import com.jyu.apts.entity.ItemProcess;
import com.jyu.apts.entity.ItemProductionLine;
import com.jyu.apts.entity.Organization;
import com.jyu.apts.entity.User;
import com.jyu.apts.service.ItemProcessService;
import com.jyu.apts.service.ItemProductionLineService;
import com.jyu.apts.service.OrganizationService;
import com.jyu.apts.service.UserService;
import com.jyu.apts.utils.AliyunOSSUtil;

@RestController
public class OrganizationItemProcessController {

	@Autowired
	ItemProcessService itemProcessService;
	@Autowired
	ItemProductionLineService itemProductionLineService;
	@Autowired
	OrganizationService organizationService;
	@Autowired
	UserService userService;
	
	@RequiresPermissions("organizationItemProcess_html")
	@RequestMapping("/organizationItemProcess_html")
	public ModelAndView organizationItemProcess_html() {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("/organizationItemProcess.html");
		return mv;
	}
	
	@RequiresPermissions("organizationItemProcess_html")
	@RequestMapping("/addOrganizationItemProcess")
	public ResultDto addOrganizationItemProcess(String name,long itemProductionLineId, int itemProcessOrder,MultipartFile image) {
		ItemProductionLine itemProductionLine = itemProductionLineService.getOne(itemProductionLineId);
		if(itemProductionLine == null) {
			return new ResultDto("流水线不存在",null,2);
		}
		UserDto userDto = (UserDto) SecurityUtils.getSubject().getSession().getAttribute("userDto");
		User orgAdmin = userService.getOne(userDto.getId());
		Organization organization = orgAdmin.getOrganization();
		if(itemProductionLine.getItem().getOrganization().getId()!=organization.getId())
			return new ResultDto("非本机构流水线",null,2);
		ItemProcess itemProcess = new ItemProcess();
		itemProcess.setName(name);
		itemProcess.setItemProcessOrder(itemProcessOrder);
		itemProcess.setItemProductionLine(itemProductionLine);
		if(image!=null) {
			String suffix = image.getOriginalFilename().substring(image.getOriginalFilename().lastIndexOf('.') + 1);
			try {
				String objectName = AliyunOSSUtil.upload(image.getInputStream(), suffix);
				itemProcess.setImage("/oss/"+objectName);
			} catch (IOException e) {
				e.printStackTrace();
				return new ResultDto("上传失败", null, 2);
			}
		}
		itemProcessService.save(itemProcess);
		return new ResultDto("添加成功",null,0);
	}
	
	@RequiresPermissions("organizationItemProcess_html")
	@RequestMapping("/upOrganizationItemProcess")
	public ResultDto upOrganizationItemProcess(long id,String name,long itemProductionLineId,int itemProcessOrder,MultipartFile image) {
		ItemProcess itemProcess = itemProcessService.getOne(id);
		if(itemProcess == null) {
			return new ResultDto("流程不存在!",null,2);
		}
		ItemProductionLine itemProductionLine = itemProductionLineService.getOne(itemProductionLineId);
		if(itemProductionLine == null) {
			return new ResultDto("流水线不存在",null,2);
		}
		UserDto userDto = (UserDto) SecurityUtils.getSubject().getSession().getAttribute("userDto");
		User orgAdmin = userService.getOne(userDto.getId());
		Organization organization = orgAdmin.getOrganization();
		if(itemProductionLine.getItem().getOrganization().getId()!=organization.getId())
			return new ResultDto("非本机构流水线",null,2);
		itemProcess.setName(name);
		itemProcess.setItemProcessOrder(itemProcessOrder);
		itemProcess.setItemProductionLine(itemProductionLine);
		if(image!=null) {
			String oldImg = itemProcess.getImage();
			if(oldImg!=null && oldImg.startsWith("/oss/")) {
				String oldObjectName =  oldImg.substring(5);
				AliyunOSSUtil.delete(oldObjectName);
			}
			String suffix = image.getOriginalFilename().substring(image.getOriginalFilename().lastIndexOf('.') + 1);
			try {
				String objectName = AliyunOSSUtil.upload(image.getInputStream(), suffix);
				itemProcess.setImage("/oss/"+objectName);
			} catch (IOException e) {
				e.printStackTrace();
				return new ResultDto("上传失败", null, 2);
			}
		}
		itemProcessService.save(itemProcess);
		return new ResultDto("更新成功",null,0);
	}
	
	@RequiresPermissions("organizationItemProcess_html")
	@RequestMapping("/delOrganizationItemProcess")
	public ResultDto delOrganizationItemProcess(String ids) {
		String[] idArray = ids.split(",");
		List<Long> l_ids = new ArrayList<Long>();
		for(String id : idArray) {
			l_ids.add(new Long(id));
		}
		List<ItemProcess> itemProcesses = itemProcessService.findAllById(l_ids);
		UserDto userDto = (UserDto) SecurityUtils.getSubject().getSession().getAttribute("userDto");
		User orgAdmin = userService.getOne(userDto.getId());
		Organization organization = orgAdmin.getOrganization();
		for(ItemProcess itemProcess : itemProcesses) {
			if(itemProcess.getItemProductionLine().getItem().getOrganization().getId()!=organization.getId())
				return new ResultDto("存在非本机构流程",null,2);
		}
		itemProcessService.delete(itemProcesses);
		return new ResultDto("删除成功",null,0);
	}
	
	@RequiresPermissions("organizationItemProcess_html")
	@RequestMapping("/getOrganizationItemProcessPage")
	public TableDto<ItemProcessDto> getOrganizationItemProcessPage(Integer pageNumber,Integer pageSize,Long itemProductionLineId,String search) {
		UserDto userDto = (UserDto) SecurityUtils.getSubject().getSession().getAttribute("userDto");
		User orgAdmin = userService.getOne(userDto.getId());
		ItemProductionLine itemProductionLine = itemProductionLineService.getOne(itemProductionLineId);
		if(itemProductionLine == null || itemProductionLine.getItem().getOrganization().getId()!=orgAdmin.getOrganization().getId()) {
			return null;
		}
		Page<ItemProcess> pageResult = itemProcessService.getItemProcessPage(pageNumber, pageSize, itemProductionLineId, search);
		List<ItemProcess> itemProcesses = pageResult.getContent();
		List<ItemProcessDto> itemProcessDtos = new ArrayList<ItemProcessDto>();
		itemProcesses.forEach(itemProcess->itemProcessDtos.add(new ItemProcessDto().convert(itemProcess)));
		return new TableDto<ItemProcessDto>(itemProcessDtos,pageResult.getTotalElements());
	}
	
	@RequiresAuthentication
	@RequestMapping("getOrganizationItemProcessByItemProductionLine")
	public List<ItemProcessDto> getOrganizationItemProcessByItem(long itemProductionLineId){
		UserDto userDto = (UserDto) SecurityUtils.getSubject().getSession().getAttribute("userDto");
		User user = userService.getOne(userDto.getId());
		ItemProductionLine itemProductionLine = itemProductionLineService.getOne(itemProductionLineId);
		if(itemProductionLine == null || itemProductionLine.getItem().getOrganization().getId()!=user.getOrganization().getId()) {
			return null;
		}
		List<ItemProcessDto> itemProcessDtos = new ArrayList<ItemProcessDto>();
		List<ItemProcess> itemProcesses = itemProductionLine.getItemProcesses();
		itemProcesses.forEach(itemProcess->itemProcessDtos.add(new ItemProcessDto().convert(itemProcess)));
		return itemProcessDtos;
	}
}
